package org.kolonitsky.translator.utils;

import java.util.ArrayList;

public class TextUtils {

    public static ArrayList<String> chunkText(String text, int limit) {
        ArrayList<String> res = new ArrayList<String>();
        res.add(text);
        char[] separators = {'.', ';', ':', ',', ' '};
        boolean proceed = true;
        for (int i = 0; proceed && i < separators.length; i++) {
            proceed = chunkText(res, separators[i], limit);
        }
        return res;
    }

    public static boolean chunkText(ArrayList<String> arr, char ch, int limit) {
        boolean res = false;
        for (int i = 0; i < arr.size(); i++) {
            String tmp = arr.get(i);
            if (tmp.length() >= limit) {
                ArrayList<String> chunks = chunkText(tmp, ch, limit);
                arr.remove(i);
                arr.addAll(i, chunks);
                res = true;
                i += chunks.size() - 1;
            }
        }
        return res;
    }

    public static ArrayList<String> chunkText(String text, char ch, int limit) {
        ArrayList<String> res = new ArrayList<String>();
        if (text.length() < limit) {
            res.add(text);
            return res;
        }
        String[] chunks = text.split("\\" + String.valueOf(ch));
        if (chunks.length == 0 || chunks.length == 1) {
            res.add(text);
            return res;
        }
        StringBuilder sb = new StringBuilder();
        for (String chunk : chunks) {
            if (sb.length() + chunk.length() > limit && sb.length() > 0) {
                res.add(sb.toString());
                sb.setLength(0);
            }
            sb = sb.append(chunk).append(ch);
        }
        if (sb.length() > 0) {
            res.add(sb.toString());
        }
        return res;
    }
}
